import jwt
import bcrypt
import os
from functools import wraps
from flask import request, current_app
from datetime import datetime, timedelta

def hash_password(password):
    """对密码进行哈希"""
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(password.encode('utf-8'), salt)

def verify_password(password, hashed):
    """验证密码"""
    return bcrypt.checkpw(password.encode('utf-8'), hashed)

def generate_token(user_id, username, expires_in=30):
    """生成JWT token"""
    payload = {
        'user_id': user_id,
        'username': username,
        'exp': datetime.utcnow() + timedelta(days=expires_in)
    }
    return jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')

def verify_token(token):
    """验证 JWT token"""
    try:
        # 添加日志
        print(f"Verifying token: {token[:20]}...")
        secret_key = os.getenv('JWT_SECRET_KEY')
        print(f"Using secret key: {secret_key[:20]}...")
        
        # 确保移除 Bearer 前缀
        if token.startswith('Bearer '):
            token = token.split(' ')[1]
        
        payload = jwt.decode(token, secret_key, algorithms=['HS256'])
        print(f"Token payload: {payload}")
        
        # 检查 token 是否过期
        if 'exp' in payload and datetime.fromtimestamp(payload['exp']) < datetime.now():
            print("Token has expired")
            return None
            
        return payload
    except jwt.InvalidTokenError as e:
        print(f"Token validation error: {str(e)}")
        return None
    except Exception as e:
        print(f"Unexpected error during token verification: {str(e)}")
        return None

def token_required(f):
    """Token验证装饰器"""
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        
        # 获取token
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(" ")[1]  # Bearer <token>
            except IndexError:
                token = auth_header
                
        if not token:
            return {'status': 'error', 'message': '缺少认证token'}, 401
            
        try:
            # 解码token
            print("Decoding token:", token)  # 添加调试日志
            data = jwt.decode(
                token,
                current_app.config['SECRET_KEY'],
                algorithms=["HS256"]
            )
            print("Decoded token data:", data)  # 添加调试日志
            
            # 设置用户信息
            request.user = {
                'user_id': data['user_id'],
                'username': data.get('username')
            }
            print("Set request.user:", request.user)  # 添加调试日志
            
        except jwt.ExpiredSignatureError:
            return {'status': 'error', 'message': 'token已过期'}, 401
        except jwt.InvalidTokenError as e:
            print("Token validation error:", str(e))  # 添加调试日志
            return {'status': 'error', 'message': '无效的token'}, 401
            
        return f(*args, **kwargs)
    return decorated 